<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/all.conf.php');
require_once(__PHY_LIB.'/inc/page.inc.php');
require_once(__PHY_LIB.'/class/uWork.class.php');
require_once(__PHY_LIB.'/class/uWorkSize.class.php');
require_once(__PHY_LIB.'/func/Cart.func.php');

/// 跳回地址 ///
$sBackUrl = get_back_url('/');
$oTpl->assign('sBack', $sBackUrl);

/// 初始化 ///
$rReq = validate($_REQUEST, 'action:e[none,add,update,delete,delete_all]');
$rMsg = array();

if ('add' == $rReq['action']) {
	do {
		if (!($rP = validate($_GET, 'id:N|size:n|kuang:n|quantity:N'))) { break; }
		if (!cart_add($rP['id'], $rP['size'], $rP['kuang'], $rP['quantity'])) { $rMsg['action'] .= 'More than stock.'; break; }
		header("Location: ?back=".urlencode($sBackUrl)); exit();
	} while (false);
}
elseif ('update' == $rReq['action']) {
	do {
		$rP = validate($_POST, 'update:r');
		$bError = false;
		foreach ($rP['update'] as $sSku => $nQ) {
			list($nI, $nS, $nK) = explode('_', $sSku);
			if (!cart_update($nI, $nS, $nK, $nQ)) { $bError = true; } //todo
		}
		if ($bError) { $rMsg['action'] .= 'More than stock.'; break; }
		header("Location: shipayment.php"); exit();
	} while (false);
}
elseif ('delete' == $rReq['action']) {
	do {
		if (!($rP = validate($_GET, 'id:N|size:n|kuang:n'))) { break; }
		cart_delete($rP['id'], $rP['size'], $rP['kuang']);
		header("Location: ?back=".urlencode($sBackUrl)); exit();
	} while (false);
}
elseif ('delete_all' == $rReq['action']) {
	do {
		cart_delete_all();
		header("Location: ?back=".urlencode($sBackUrl)); exit();
	} while (false);
}

/// 得到购物车信息 ///
$rCart = cart_fetch();
/// 购物车里的作品列表 ///
foreach ($rCart as $k => $r) {
	$oWork = new uWork($r['ItemID']);
	$oWork->set('size_id', $r['SizeID']);
	$oWork->set('kuang_id', $r['KuangID']);
	$oWork->set('Sku', "{$r['ItemID']}_{$r['SizeID']}_{$r['KuangID']}");
	if (0 < $r['SizeID']) {
		$oWorkSize = new uWorkSize($r['SizeID']);
		$oWork->set('size_title', $oWorkSize->get('title'));
		$oWork->set('size_title_en', $oWorkSize->get('title_en'));
	}
	$oWork->getSku($r['SizeID'], $r['KuangID'], true);
	$rCart[$k]['Item'] = $oWork->getData();
}
$oTpl->assign('rCart', $rCart);
//@ echo '<pre>'; print_r($rCart); echo '<pre>';

$oTpl->assign('rMsg', $rMsg);
$oTpl->display(dirname(__FILE__).'/'.basename(__FILE__, '.php').'.tpl');
?>
